package com.sctu.edu.tracks.fragment;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.sctu.edu.tracks.R;
import com.sctu.edu.tracks.bean.RecordListBean;
import com.sctu.edu.tracks.config.URLConfig;
import com.sctu.edu.tracks.utils.L;
import com.sctu.edu.tracks.utils.httputils.GetVolleyHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by zhengsenwen on 2017/3/8.
 */

public class Fragment1 extends Fragment implements LocationSource, AMapLocationListener {
    private MapView mapView;
    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
    private Button startStop;
    private Polyline polyline;
    private boolean flag = false;
    private double lat, lng, alt;
    private String username, recordName;
    private Map<String, String> mapPoi = new HashMap<String, String>();
    private List<LatLng> latLngs = new ArrayList<LatLng>();
    private Activity activity;
    private UiSettings uiSettings;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        activity = getActivity();
        View view = LayoutInflater.from(activity).inflate(R.layout.main_map, null);
        startStop = (Button) activity.findViewById(R.id.btn_start_stop);

        username = activity.getIntent().getExtras().getString("username");
        recordName = username + UUID.randomUUID().toString();

        //获取地图控件引用
        mapView = (MapView) view.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);

        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.setLocationSource(this);
            aMap.setMyLocationEnabled(true);
            aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
        } else {
            aMap = mapView.getMap();
            aMap.setLocationSource(this);
            aMap.setMyLocationEnabled(true);
            aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
        }

        //设置定位参数
        setLocation();
        //设置手势
        setUiSettings();

        return view;
    }

    private void setUiSettings() {
        uiSettings = aMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(true);
        uiSettings.setCompassEnabled(true);
        uiSettings.setZoomControlsEnabled(true);
        uiSettings.setZoomControlsEnabled(true);
        uiSettings.setScaleControlsEnabled(true);

        uiSettings.setAllGesturesEnabled(true);
    }

    /**
     * 设置定位参数和小蓝点
     */

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {

                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                lat = aMapLocation.getLatitude();
                lng = aMapLocation.getLongitude();
                alt = aMapLocation.getAltitude();
                L.e("lat", lat + "  " + lng + "  " + alt);

                //动态添加坐标，绘制线路
                latLngs.add(new LatLng(lat, lng));
                polyline = aMap.addPolyline(new PolylineOptions().
                        addAll(latLngs).width(30).color(Color.argb(255, 1, 1, 1)));

                LatLng latLng = new LatLng(lat,lng);
                aMap.addMarker(new MarkerOptions()
                        .position(latLng).title("我的位置").snippet("DefaultMarker"));

                startStop.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (flag) {
                            flag = false;
                            startStop.setText("开始");
                            //使用新的recordName
                            recordName = username + UUID.randomUUID().toString();
                        } else {
                            flag = true;
                            startStop.setText("结束");
                            //与服务器建立连接
                            createConnection();
                            //每隔2秒上传一次坐标信息
                            Runnable runnable = new Runnable() {
                                @Override
                                public void run() {
                                    while (flag == true) {
                                        uploadPoi(lat, lng, alt);
                                        try {
                                            Thread.sleep(2000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            };
                            Thread thread = new Thread(runnable);
                            thread.start();
                        }
                    }
                });

            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                L.e("AmapErr", errText);
            }
        }
    }


    /**
     * 上传坐标数据
     */
    private void uploadPoi(Double lat, Double lng, Double alt) {
        mapPoi.put("recordName", recordName);
        mapPoi.put("latitude", String.valueOf(lat));
        mapPoi.put("longitude", String.valueOf(lng));
        mapPoi.put("height", String.valueOf(alt));

        Response.Listener<String> recordPoiListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                L.e("recordPoi", json);
            }
        };
        Response.ErrorListener errorPoiListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(activity, "网络出了点小问题", Toast.LENGTH_SHORT).show();
                L.e("recordFail", volleyError.getMessage() + "");
            }
        };
        GetVolleyHttp.getInstance(activity).getStringPOSTJsonData(
                URLConfig.RECORD_POIS, (HashMap<String, String>) mapPoi, recordPoiListener, errorPoiListener);
    }

    /**
     * 点击开始，与服务器建立连接
     */
    private void createConnection() {
        Map<String, String> mapConn = new HashMap<String, String>();
        mapConn.put("recordName", recordName);

        Response.Listener<String> startRecordListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String json) {
                L.e("start", json);
                RecordListBean recordListBean = JSON.parseObject(json, RecordListBean.class);
                if (200 == recordListBean.getCode()) {
                    Toast.makeText(activity, "连接服务器成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(activity, "网络出了点小问题", Toast.LENGTH_SHORT).show();
                }
            }
        };
        Response.ErrorListener errorStartListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(activity, "网络出了点小问题", Toast.LENGTH_SHORT).show();
            }
        };
        GetVolleyHttp.getInstance(activity).getStringPOSTJsonData(
                URLConfig.START_RECORD, (HashMap<String, String>) mapConn, startRecordListener, errorStartListener);
    }

    private void setLocation() {
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(2000);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setMockEnable(true);
        mLocationOption.setHttpTimeOut(80000);

        myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
        myLocationStyle.showMyLocation(true); //设置是否显示定位小蓝点
        myLocationStyle.strokeColor(Color.BLUE);

        //3D立体的地图就是这么来的,2D的是：
        //myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);
        //aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
        myLocationStyle.radiusFillColor(Color.WHITE);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mLocationClient == null) {
            //初始化定位
            mLocationClient = new AMapLocationClient(activity);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mLocationClient.startLocation();//启动定位
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mapView.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

}
